package com.app.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.app.common.Result;
import com.app.config.RedisService;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.IPurchaseCouponsRecordService;
import com.app.service.InviteConfigService;
import com.app.service.InviteRecordService;
import com.app.service.UserService;
import com.app.utils.CommonHelp;
import com.app.utils.PriceUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 我的购劵记录表 服务实现类
 * </p>
 *
 * @author yoominic
 * @since 2024-09-03
 */
@Slf4j
@Service
public class PurchaseCouponsRecordServiceImpl extends ServiceImpl<PurchaseCouponsRecordMapper, PurchaseCouponsRecord> implements IPurchaseCouponsRecordService {
    @Autowired
    private PurchaseCouponsRecordMapper purchaseCouponsRecordMapper;
    @Value("${wx.new.pay.rechargeNotify}")
    private String rechargeNotify;
    @Value("${wx.new.pay.mchId}")
    private String newMchId;
    @Autowired
    private UserService userService;
    @Autowired
    private WxPayService wxService;
    @Autowired
    private InviteConfigMapper inviteConfigMapper;
    @Autowired
    private IntegralRecordMapper integralRecordMapper;
    @Autowired
    private VoucherRecordMapper voucherRecordMapper;
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private InviteConfigService inviteConfigService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MessageBoxMapper messageBoxMapper;
    @Autowired
    private InviteRecordService inviteRecordService;
    @Autowired
    private UserMapper userMapper;


    @Override
    public Result buyAcount(BigDecimal money, UserModel userModel) {
        List<InviteConfigModel> inviteConfigModelList = inviteConfigService.list();
        // 微信支付
        // 回调 1、当前用户加劵  2、消息盒子  3、记录表加记录
        String orderSn = IdUtil.fastSimpleUUID();
        String openId = userModel.getLoginOpenid();
        String ip = userModel.getIp();
        WxPayUnifiedOrderRequest requestBody = new WxPayUnifiedOrderRequest();
        requestBody.setAttach("益联劵充值");
        requestBody.setBody("益联劵充值");
        requestBody.setOutTradeNo(orderSn);
        requestBody.setTotalFee(PriceUtils.changeY2F(money.doubleValue()));
        requestBody.setSpbillCreateIp("8.8.8.8");
        requestBody.setNotifyUrl(rechargeNotify);
        requestBody.setOpenid(openId);

        requestBody.setTradeType(WxPayConstants.TradeType.JSAPI);


        // tb_purchase_coupons_record 充值记录表加记录
        PurchaseCouponsRecord purchaseCouponsRecord = new PurchaseCouponsRecord();
        purchaseCouponsRecord.setAmount(money);
        purchaseCouponsRecord.setStatus(1);
        purchaseCouponsRecord.setOrderSn(orderSn);
        purchaseCouponsRecord.setCreateTime(LocalDateTime.now());
        purchaseCouponsRecord.setUserId(userModel.getId());
        this.purchaseCouponsRecordMapper.insert(purchaseCouponsRecord);
        try {

            Object response = this.wxService.switchoverTo(newMchId).createOrder(requestBody);
            log.info(JSONUtil.toJsonStr(response));
            JSONObject object = JSONUtil.parseObj(response);
            object.set("package", object.getStr("packageValue"));
            object.set("prePayParams", newMchId);
            object.set("orderSn", orderSn);
            return Result.success(object);
        } catch (Exception e) {
            log.info("请求失败,{}", e.getMessage());
            e.printStackTrace();
        }
        return Result.success(null);
    }


    @Override
    public Result getList(Integer userId) {
        QueryWrapper<PurchaseCouponsRecord> purchaseCouponsRecordQueryWrapper = new QueryWrapper<>();
        purchaseCouponsRecordQueryWrapper.eq("user_id", userId);
        purchaseCouponsRecordQueryWrapper.eq("status", 2);
        purchaseCouponsRecordQueryWrapper.orderByDesc("buy_time");
        return Result.success(this.purchaseCouponsRecordMapper.selectList(purchaseCouponsRecordQueryWrapper));
    }

    @Override
    public Integer rechargeCallback(String outTradeNo) {
        QueryWrapper<PurchaseCouponsRecord> purchaseCouponsRecordQueryWrapper = new QueryWrapper<>();
        purchaseCouponsRecordQueryWrapper.eq("order_sn", outTradeNo);
        PurchaseCouponsRecord purchaseCouponsRecord = this.purchaseCouponsRecordMapper.selectOne(purchaseCouponsRecordQueryWrapper);
        if (purchaseCouponsRecord.getStatus() == 1) {
            purchaseCouponsRecord.setStatus(2);
            purchaseCouponsRecord.setBuyTime(LocalDateTimeUtil.now());
            this.purchaseCouponsRecordMapper.updateById(purchaseCouponsRecord);
            //给用户加券
            UserModel userModel = this.userService.getById(purchaseCouponsRecord.getUserId());
            if (userModel != null) {
                BigDecimal voucher = BigDecimal.valueOf(userModel.getVoucher()).add(purchaseCouponsRecord.getAmount()).setScale(2, RoundingMode.HALF_DOWN);
                userModel.setVoucher(voucher.doubleValue());

                InviteConfigModel inviteConfig = inviteConfigMapper.selectById(1);
                BigDecimal integralValue = purchaseCouponsRecord.getAmount().multiply(BigDecimal.valueOf(inviteConfig.getConversion()));//根据比例转换的积分
                BigDecimal newIntegral = integralValue.add(BigDecimal.valueOf(userModel.getIntegral())).setScale(2, RoundingMode.HALF_DOWN);
                userModel.setIntegral(newIntegral.doubleValue());

                this.userService.updateById(userModel);

                //新增积分记录
                IntegralRecordModel integralRecordModel = new IntegralRecordModel();
                integralRecordModel.setName("充值益联券得积分");
                integralRecordModel.setTypeName("充值益联券得积分");
                integralRecordModel.setContent("充值" + purchaseCouponsRecord.getAmount() + "益联券");
                String amountIntegral = String.format("+%.2f分", integralValue.doubleValue());
                integralRecordModel.setIntegral(amountIntegral);
                integralRecordModel.setUserId(userModel.getId());
                integralRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
                integralRecordModel.setVoucherType(1);
                integralRecordModel.setVoucherAmount(integralValue.doubleValue());
                integralRecordMapper.insert(integralRecordModel);

                //增加益联券记录
                VoucherRecordModel voucherRecordModel = new VoucherRecordModel();
                voucherRecordModel.setName("充值益联券");
                voucherRecordModel.setTypeName("充值益联券");
                String amountVoucher = "+" + purchaseCouponsRecord.getAmount().doubleValue() + "券";
                voucherRecordModel.setVoucher(amountVoucher);
                voucherRecordModel.setUserId(userModel.getId());
                voucherRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
                voucherRecordModel.setVoucherType(1);
                voucherRecordModel.setVoucherAmount(purchaseCouponsRecord.getAmount().doubleValue());
                voucherRecordModel.setWriteOff(1);
                voucherRecordMapper.insert(voucherRecordModel);

                //拿到成为会员的金额数 好做比较
                List<InviteConfigModel> inviteConfigModelList = inviteConfigService.list();
                BigDecimal vipPrice=new BigDecimal(inviteConfigModelList.get(0).getVipPrice());
                System.err.println("vipPrice:"+vipPrice.doubleValue());
                System.err.println("充值的钱数:"+purchaseCouponsRecord.getAmount().doubleValue());

                // 设置相同的小数位
                BigDecimal amount = purchaseCouponsRecord.getAmount().setScale(3, RoundingMode.HALF_UP);
                vipPrice = vipPrice.setScale(3, RoundingMode.HALF_UP);
                if (amount.compareTo(vipPrice) >= 0
                        && userModel.getVip() != 1) {//充值的钱数大于等于会员钱数

                    //分配会员权限
                    try {
                        // 设置用户为会员
                        userServiceImpl.updateUserInfo(userModel);
                        //消息盒子
                        MessageBoxModel message = new MessageBoxModel();
                        message.setUserId(userModel.getId());
                        message.setTypeName("开通会员成功通知");
                        message.setVoucher(purchaseCouponsRecord.getAmount().doubleValue());
                        message.setNotes("充值会员奖励益联券");
                        message.setCreateTime(CommonHelp.getNowTimestamp());
                        message.setOrderSn(outTradeNo);
                        messageBoxMapper.insert(message);

                        //邀请关系
                        QueryWrapper<InviteRecordModel> inviteRecordModelQueryWrapper = new QueryWrapper<>();
                        inviteRecordModelQueryWrapper.eq("quilt_invite_id", userModel.getId());
                        InviteRecordModel recordModel = inviteRecordService.getOne(inviteRecordModelQueryWrapper);
                        if (recordModel != null) {
                            QueryWrapper<InviteRecordModel> inviteRecordModelQueryWrapper1 = new QueryWrapper<>();
                            inviteRecordModelQueryWrapper1.eq("invite_id", recordModel.getInviteId())
                                    .eq("status", 2)
                                    .eq("is_act", 1);
                            inviteRecordModelQueryWrapper1.orderByDesc("create_time");
                            List<InviteRecordModel> recordModelList = inviteRecordService.list(inviteRecordModelQueryWrapper1);

                            UserModel inviteUser = userMapper.selectById(recordModel.getInviteId());
                            int count = recordModelList.size() + 1;
                            if (count == (inviteConfig.getInviteCount())) {
                                inviteUser.setVoucher(inviteUser.getVoucher() + inviteConfig.getInviteVoucher());
                                userMapper.updateById(inviteUser);
                                //新增券记录
                                VoucherRecordModel voucherRecordModel1 = new VoucherRecordModel();
                                voucherRecordModel1.setName("邀请好友获得益联券");
                                voucherRecordModel1.setTypeName("邀请好友");
                                String amountIntegral2 = "+" + inviteConfig.getInviteVoucher()+ "券";
                                voucherRecordModel1.setVoucher(amountIntegral2);
                                voucherRecordModel1.setUserId(inviteUser.getId());
                                voucherRecordModel1.setCreateTime(CommonHelp.getNowTimestamp());
                                voucherRecordModel1.setVoucherType(1);
                                voucherRecordModel1.setVoucherAmount(Double.valueOf(inviteConfig.getInviteVoucher()));
                                voucherRecordMapper.insert(voucherRecordModel1);
                                //
                                recordModel.setStatus(2);
                                recordModel.setIsAct(0);
                                inviteRecordService.updateById(recordModel);
                                //消息盒子记录数据
                                MessageBoxModel messageBoxModel = new MessageBoxModel();
                                messageBoxModel.setUserId(inviteUser.getId());
                                messageBoxModel.setQuiltUserId(inviteUser.getId());
                                messageBoxModel.setTypeName("奖励通知");
                                messageBoxModel.setVoucher(Double.valueOf(inviteConfig.getInviteVoucher()));
                                messageBoxModel.setNotes("邀请好友满足额度");
                                messageBoxModel.setCreateTime(CommonHelp.getNowTimestamp());
                                messageBoxModel.setOrderSn(outTradeNo);
                                messageBoxMapper.insert(messageBoxModel);
                                //使曾经邀请的人邀请关系失效
                                recordModelList.stream().forEach(s -> s.setIsAct(0));
                                this.inviteRecordService.updateBatchById(recordModelList);
                            } else {
                                recordModel.setStatus(2);
                                recordModel.setIsAct(1);
                                inviteRecordService.updateById(recordModel);
                            }
                        }
                    } catch (Exception e) {
                        log.info("升级会员权限失败:{}", e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
